package com.powermgr.boringtest.utils;
import lombok.extern.log4j.Log4j2;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * RootUtils
 *
 * @author qiuxiangdong
 * @date 2023/11/21 14:13
 */
@Log4j2
public class RootUtils {
    public static boolean goRoot(String imgPath, String toolPath, String sn, String ld
    ) {
        boolean root = rk3568Upgrade(imgPath, toolPath, sn, ld);
        if (root){
            String limiting = String.format("hdc -t %s shell hilog -Q pidoff", ld);
            String limitingLog = sendCmd(limiting);
            log.info(limitingLog);
            String debug = String.format("hdc -t %s shell hilog -b D", ld);
            String debugLog = sendCmd(debug);
            log.info(debugLog);
            log.info("rk3568_upgrade end!");
            return true;
        } else {
            return false;
        }
    }

    private static boolean rk3568Upgrade(String imgPath, String toolPath, String sn, String ld) {
        log.info(sn + "enter loader mode...!");
        String rebootLoader = String.format("hdc -t %s shell reboot loader", sn);
        String rl = sendCmd(rebootLoader);
        log.info(rl);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        String upgradeLoaderCmd = String.format("%s -s %s UL %s/MiniLoaderAll.bin -noreset", toolPath, ld, imgPath);
        String h = sendCmd(upgradeLoaderCmd);
        log.info(h);
        if (!h.contains("Upgrade loader ok")) {
            log.error("Download MiniLoaderAll.bin Fail!");
            return false;
        } else {
            log.info("Download MiniLoaderAll.bin Success!");
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        String write_gpt_cmd = String.format("%s -s %s DI -p %s/parameter.txt", toolPath, ld, imgPath);
        String j = sendCmd(write_gpt_cmd);
        log.info(j);
        if (!j.contains("Write gpt ok")) {
            log.error("Failed to execute the parameter.txt");
            return false;
        } else {
            log.info("The uboot.image downloaded successfully!");
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        if (!flashVersion(imgPath, toolPath, ld)) {
            return false;
        }

        String reboot_devices_cmd = String.format("%s -s %s RD", toolPath, ld);
        String reboot_result = sendCmd(reboot_devices_cmd);
        log.info(reboot_result);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        String power_cmd = String.format("hdc -t %s shell power-shell setmode 602", sn);
        String power_result = sendCmd(power_cmd);
        log.info(power_result);
        int number = 0;
        while (!power_result.contains("Set Mode Success") && number < 60) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error(e);
            }
            power_result = sendCmd(power_cmd);
            log.info(power_result);
            number++;
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            log.error(e);
        }
        if (!reboot_result.contains("Reset Device OK")) {
            log.error("Failed to reboot the board!");
            return false;
        } else {
            log.info("Reboot successfully!");
            log.info("******DownLoader img Finished and upload successfully******");
            return true;
        }
    }
    private static boolean flashVersion(String imgPath, String toolPath, String ld) {
        String[] partList = {"boot_linux", "system", "vendor", "userdata", "resource", "ramdisk", "chipset", "sys-prod", "chip-prod", "updater"};
        for (String i : partList) {
            if (!new File(String.format("%s/%s.img", imgPath, i)).exists()) {
                log.error(i + "img is not exist, ignore.");
                continue;
            }
            String loadCmd = String.format("%s -s %s DI -%s %s/%s.img", toolPath, ld, i, imgPath, i);
            String p = sendCmd(loadCmd);
            log.info(p);
            if (!p.contains("Download image ok")) {
                log.error("Failed to download the " + i + ".img!");
                return false;
            } else {
                log.info("The " + i + ".img downloaded successfully!");
            }
        }
        return true;
    }

    private static String sendCmd(String cmd) {
        StringBuilder result = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            process.waitFor();
            bufferedReader.close();
        } catch (IOException | InterruptedException e) {
            log.error(e);
        }
        return result.toString();
    }
}
